import 'dart:convert';

import 'package:elephant_fish/dao/login_dao.dart';
import 'package:elephant_fish/http/core/hi_error.dart';
import 'package:elephant_fish/model/user_info_entity.dart';
import 'package:elephant_fish/util/TxUtils.dart';
import 'package:elephant_fish/util/size_util.dart';
import 'package:elephant_fish/util/string_util.dart';
import 'package:elephant_fish/util/toast.dart';
import 'package:elephant_fish/widget/login_button.dart';
import 'package:elephant_fish/widget/login_input.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:shared_preferences/shared_preferences.dart';

class LoginPage extends StatefulWidget {
  final int loginCode;
  final Map arguments;

  const LoginPage({Key key, this.loginCode, this.arguments}) : super(key: key);

  @override
  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  DateTime lastPopTime;
  bool loginEnable = false;
  String phone;
  String password;

  @override
  Future<void> initState() {
    // TODO: implement initState
    super.initState();
    initial();
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      child: Scaffold(
        backgroundColor: Color(0xff140c3c),
        body: SingleChildScrollView(
            child: Column(
          children: [
            Container(
              width: double.infinity,
              decoration: BoxDecoration(
                borderRadius: BorderRadius.only(
                    bottomLeft: Radius.circular(SizeUtil.px(40)),
                    bottomRight: Radius.circular(SizeUtil.px(40))),
                image: DecorationImage(
                    image: AssetImage('assets/images/login_bg.png')),
              ),
              child: Column(
                children: [
                  SizedBox(
                    height: SizeUtil.px(205),
                  ),
                  Center(
                    child: Container(
                      width: SizeUtil.px(142),
                      height: SizeUtil.px(142),
                      decoration: BoxDecoration(
                        borderRadius:
                            BorderRadius.all(Radius.circular(SizeUtil.px(72))),
                        color: Color(0xffe9e2eb),
                      ),
                      child: Center(
                        child: Image.asset(
                          'assets/images/login_logo.png',
                          width: SizeUtil.px(96.67),
                          height: SizeUtil.px(93.79),
                        ),
                      ),
                    ),
                  ),
                  SizedBox(
                    height: SizeUtil.px(75),
                  ),
                  Align(
                    alignment: Alignment.bottomCenter,
                    child: Container(
                      width: SizeUtil.px(563),
                      child: Column(
                        children: [
                          LoginInput(
                            '邮箱/手机号',
                            obscureText: false,
                            onChanged: (text) {
                              phone = text;
                              checkInput();
                            },
                          ),
                          Container(
                            width: SizeUtil.px(563),
                            height: SizeUtil.px(1),
                            color: Color(0xff707070),
                          )
                        ],
                      ),
                    ),
                  ),
                  Align(
                    alignment: Alignment.bottomCenter,
                    child: Container(
                      width: SizeUtil.px(563),
                      child: Column(
                        children: [
                          LoginInput(
                            '密码',
                            obscureText: true,
                            onChanged: (text) {
                              password = text;
                              checkInput();
                            },
                          ),
                          Container(
                            width: SizeUtil.px(563),
                            height: SizeUtil.px(1),
                            color: Color(0xff707070),
                          )
                        ],
                      ),
                    ),
                  ),
                ],
              ),
            ),
            Container(
              //控件高度
              constraints: new BoxConstraints.expand(
                height: 357.5,
              ),
              //设置背景图片
              decoration: new BoxDecoration(
                color: Color(0xff140c3c),
              ),
              alignment: Alignment.bottomCenter,
              child: ListView(
                children: [
                  Padding(
                    padding: EdgeInsets.only(left: 20, right: 20, top: 20),
                    child: LoginButton(
                      '登录',
                      enable: loginEnable,
                      onPressed: send,
                    )),
                  Padding(
                    padding: EdgeInsets.only(left: 20, right: 20, top: 20),
                    child: Row(
                      children: [
                        InkWell(
                          onTap: () {
                            Navigator.pushNamed(context, '/reset/password');
                            print('忘记密码');
                          },
                          child: Text(
                            '忘记密码？',
                            style: TextStyle(color: Color(0xffe62d6c)),
                          ),
                        ),
                        Spacer(),
                        InkWell(
                          onTap: () {
                            Navigator.pushNamed(context, '/login/register');
                            print('手机注册');
                          },
                          child: Text(
                            '手机注册',
                            style: TextStyle(color: Color(0xffe62d6c)),
                          ),
                        ),
                      ],
                    )),
                ],
              ),
            ),
          ],
        )),
      ),
      onWillPop: () async {
        if (lastPopTime == null ||
            DateTime.now().difference(lastPopTime) > Duration(seconds: 2)) {
          lastPopTime = DateTime.now();
          TxUtils.showToast('再按一次退出', context);
        } else {
          lastPopTime = DateTime.now();
          // 退出app
          await SystemChannels.platform.invokeMethod('SystemNavigator.pop');
        }
      },
    );
  }

  void send() async {
    try {
      var result =
          await LoginDao.login(phone, type: 'password', password: password);
      print(result);
      if (result['code'] == 0) {
        print('app_token' + result['data']['app_token']);
        Map<String,dynamic> map = new Map<String, dynamic>.from(result['data']);
        UserInfoEntity _userInfoEntity = UserInfoEntity.fromJson(map);
        SharedPreferences prefs = await SharedPreferences.getInstance();
        prefs.setString('USERINFO', jsonEncode(_userInfoEntity));
        TxUtils.setStorageByKey('UserId', _userInfoEntity.userId);
        TxUtils.setStorageByKey('loginUserName', _userInfoEntity.nickname == '' || _userInfoEntity.nickname == null ? '暂未设置名称' : _userInfoEntity.nickname);
        TxUtils.showToast('登录成功', context);
        if(_userInfoEntity.nickname == null || _userInfoEntity.nickname == ''){
          Navigator.pushNamed(context, '/register/perfectInformation');
        }else{
          Navigator.pushNamed(context, '/index');
        }
      } else {
        print(result['message']);
        TxUtils.showErrorToast(result['message'], context);
      }
    } on NeedAuth catch (e) {
      print(e);
      showWarnToast(e.message);
    } on HiNetError catch (e) {
      print(e);
      showWarnToast(e.message);
    }
  }

  void checkInput() {
    bool enable;
    if (isNotEmpty(phone) && isNotEmpty(password)) {
      enable = true;
    } else {
      enable = false;
    }
    setState(() {
      loginEnable = enable;
    });
  }

  Future<void> initial() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String appToken = prefs.getString("app-token");
    if (appToken != null) {
      if (appToken.isNotEmpty ) {
        if (widget.arguments == null) {
          Navigator.of(context).pop();
          Navigator.pushNamed(context, '/index');
        } else if (widget.arguments['loginCode'] != '-1') {
          Navigator.of(context).pop();
          Navigator.pushNamed(context, '/index');
        }
      }
    }
  }
}
